package com.atmilan.quartz.utils.source;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.CategoryTypeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.StockAreaTempEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.jst.JstProduct;
import com.atmilan.quartz.model.entity.jst.JstProductSku;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.ISupplierService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import lombok.extern.log4j.Log4j2;

/**
 * 聚水潭
 * @author daigb
 * @date:  2022-02-23 14:41
 */
@Log4j2
@Service
public class SourceJstProductUtil {
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ISupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;

    /**
     * 构建DO对象
     * @Description:  
     * @author daigb 
     * @param @param product
     * @param @param productSkus
     * @param @return
     * @return StoreProductRequest
     * @throws
     */
    public StoreProductCrmebRequest buildCrmebProduct(JstProduct product, List<JstProductSku> skus, int stock) {
        StoreProductCrmebRequest productRequest = null;
    	// 成本价
        BigDecimal price = null == product.getSPrice() ? BigDecimal.ZERO : new BigDecimal(product.getSPrice());
        // 原价欧元
        BigDecimal otPrice = null == product.getMarketPrice() ? BigDecimal.ZERO : priceUtil.rmb2EurStatic(new BigDecimal(product.getMarketPrice()));
//        if(price.compareTo(BigDecimal.ZERO) == 0) {
//        	return null;
//        }
    	
        // 品牌对应
        StoreBrand storeBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                .eq(StoreBrand :: getEnName, product.getBrand())
                .eq(StoreBrand :: getType, ProductTypeEnum.JST)
                .last("LIMIT 1")
                );
        storeBrandService.unMatchBrand(storeBrand,null,product.getBrand(),ProductTypeEnum.JST);
        if(null != storeBrand && null != storeBrand.getSuperId()) {
            storeBrand = storeBrandService.getById(storeBrand.getSuperId());
        }else {
            storeBrand = storeBrandService.getById(5429);
        }
        
        /***** 处理对象构建 *******/
        String barCode = BarCodeEnum.JST.getCode() + product.getIId();
        List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
        List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();
        // 规格
        StoreProductAttr storeProductAttr = new StoreProductAttr();
        storeProductAttr.setAttrName("尺寸");
        storeProductAttr.setType(0);
        // 颜色
        StoreProductAttr storeProductAttrColor = new StoreProductAttr();
        storeProductAttrColor.setAttrName("颜色");
        storeProductAttrColor.setType(0);
        // 轮播图
        JSONArray sliderImage = new JSONArray();
        
        // 合并成suk
        List<String> colorValueList = new ArrayList<String>();
        List<String> valueList = new ArrayList<String>();
        for(JstProductSku sku : skus) {
        	if(StringUtils.isNotBlank(sku.getPic())) {
        		sliderImage.add(sku.getPic());
        	}
        	
        	BigDecimal valuePrice = price;
            StoreProductAttrValueRequest storeProductAttrValueRequest = new StoreProductAttrValueRequest();
            storeProductAttrValueRequest.setSourceSkuId(sku.getSkuId());
            storeProductAttrValueRequest.setPromotePrice(BigDecimal.ZERO);
            storeProductAttrValueRequest.setPrice(valuePrice);
            storeProductAttrValueRequest.setStock(sku.getQty());
            storeProductAttrValueRequest.setBarCode(barCode);

            BigDecimal skuOtPrice = otPrice;
            storeProductAttrValueRequest.setOtPrice(skuOtPrice);
            storeProductAttrValueRequest.setCost(valuePrice);
            storeProductAttrValueRequest.setSourceCost(valuePrice);
            storeProductAttrValueRequest.setImage(sku.getPic());

            LinkedHashMap<String, String> linkedMap = new LinkedHashMap<String, String>();
            List<String> suk = new ArrayList<String>();
            String sukStr = sku.getPropertiesValue();
            String color = "默认";
            if (StringUtils.isNotBlank(color)) {
                linkedMap.put("颜色", color);
                if(!colorValueList.contains(color)){
                    colorValueList.add(color);
                }
                suk.add(color);
            }
            String size = sukStr;
            if (StringUtils.isNotBlank(size)) {
                linkedMap.put("尺寸", size);
                if(!valueList.contains(size)){
                    valueList.add(size);
                }
                suk.add(size);
            }
            
            storeProductAttrValueRequest.setSuk(String.join(",", suk));
            storeProductAttrValueRequest.setAttrValue(linkedMap);
            storeProductAttrValueRequest.setTempId(StockAreaTempEnum.EUR.getTempId());
            attrValueList.add(storeProductAttrValueRequest);
        }
        if (CollectionUtils.isNotEmpty(colorValueList)) {
            storeProductAttrColor.setAttrValues(String.join(",", colorValueList));
            attrList.add(storeProductAttrColor);
        }
        if (CollectionUtils.isNotEmpty(valueList)) {
            storeProductAttr.setAttrValues(String.join(",", valueList));
            attrList.add(storeProductAttr);
        }
//        if(CollectionUtils.isEmpty(sliderImage)) {
//        	return null;
//        }

        productRequest = new StoreProductCrmebRequest();
//        productRequest.setExchangeRate(new BigDecimal(PriceUtil.DEFAULT_EXCHANGE_RATE_EUR));

        // 抽取所有size属性去重
        productRequest.setAttr(attrList);
        productRequest.setAttrValue(attrValueList);
        // 强制写一个 商户id 作为buyer商品标识标识
        productRequest.setMerId(CrmebMerchantEnums.JST.getMerchantId());
        productRequest.setContent(product.getName());
        productRequest.setKeyword(getKeyword(product.getIId()));
        productRequest.setStock(stock);
        productRequest.setStoreInfo(product.getName());
        productRequest.setStoreName(product.getName());
        productRequest.setBrandId(storeBrand.getId());
        productRequest.setBrandName(product.getBrand());
        productRequest.setPrice(price);
        productRequest.setOtPrice(otPrice);
        productRequest.setCost(price);
        productRequest.setSourceCost(price);
        productRequest.setPromoteFlag(false);
        productRequest.setErpPromFlag(true);

        // 供应商
        Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                .eq(Supplier :: getBarcode, BarCodeEnum.JST.getCode())
                .last("LIMIT 1")
                );
        productRequest.setSuppliersId(supplier.getId());
        productRequest.setSuppliersName(supplier.getSuppliersName());
        BigDecimal exchangeRate = priceUtil.getMoneyExchange(supplier.getCurrencyId());
        productRequest.setExchangeRate(exchangeRate);
        // 分类
        CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                .eq(CategoryMatch :: getType, CategoryTypeEnum.JST)
                .eq(CategoryMatch :: getCategoryName, product.getVcName())
                .last("LIMIT 1")
                );
        categoryMatchService.unMatchCategory(categoryMatch,null,product.getVcName(),null,CategoryTypeEnum.JST);
        // 复制重量
        if(null != categoryMatch) {
        	CategoryMatch supCategoryMatch = categoryMatchService.getById(categoryMatch.getCategoryId());
        	categoryMatch.setWeight(Optional.ofNullable(supCategoryMatch).orElse(new CategoryMatch()).getWeight());
        }
        Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 1859;
        productRequest.setBarCode(barCode);
        productRequest.setCateId(categoryId);
        productRequest.setCateIds(Arrays.asList(categoryId));
        productRequest.setWeight(null != product.getWeight() ? new BigDecimal(product.getWeight()) : null != categoryMatch ? categoryMatch.getWeight() : BigDecimal.ONE);
        productRequest.setImage(0 < sliderImage.size() ? sliderImage.get(0).toString() : "");
        productRequest.setSliderImage(sliderImage.toJSONString());
        productRequest.setIsShow(true);
        productRequest.setSort(0);
        productRequest.setSpecType(true);
        productRequest.setIsEurope(ProductTypeEnum.JST.getCode());
        productRequest.setTempId(StockAreaTempEnum.HK.getTempId());
        productRequest.setUnitName("件");
        productRequest.setLastPushTime(new Date());
        productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
        
        return productRequest;
    }
    
    private String getKeyword(String keyword) {
    	// 去掉打头符号, 去掉空格和后面所有数据
    	if(keyword.startsWith("CL&") || keyword.startsWith("GK&") || keyword.startsWith("HY&") || keyword.startsWith("JP&")
    			 || keyword.startsWith("KL&") || keyword.startsWith("KX&") || keyword.startsWith("LDY&")
    			 || keyword.startsWith("OP&") || keyword.startsWith("SS&") || keyword.startsWith("VK&") || keyword.startsWith("YSS&")) {
    		return keyword.replaceFirst("CL&", "").replaceFirst("GK&", "").replaceFirst("HY&", "").replaceFirst("JP&", "").replaceFirst("KL&", "")
    		.replaceFirst("KX&", "").replaceFirst("LDY&", "").replaceFirst("OP&", "").replaceFirst("SS&", "").replaceFirst("VK&", "")
    		.replaceFirst("YSS&", "").split(" ")[0];
    	}
    	// 去掉打头符号, 所有空格合并, 中划线合并
    	if(keyword.startsWith("LJ&")) {
    		return keyword.replaceFirst("LJ& ", "").replaceFirst("LJ&1", "").replaceFirst("LJ&2", "").replaceFirst("LJ&3", "")
    				.replaceFirst("LJ&Z", "").replaceAll(" ", "").replaceAll("- ", "");
    	}
    	// 去掉打头符号, 所有空格合并, 中划线合并
    	if(keyword.startsWith("PH-")) {
    		return keyword.replaceFirst("PH-", "").replaceAll(" ", "").replaceAll("- ", "");
    	}
    	// 一个空格只截取空格前面
    	if(keyword.contains(" ")) {
    		return keyword.split(" ")[0];
    	}
    	// 一个或多个横杠直接合并
    	if(keyword.contains("-")) {
    		return keyword.split("-")[0];
    	}
    	
    	return keyword;
    }

}
